<template>
    <div class="security-part-div">
        <el-row type="flex" jusify="center">
            <el-col :span="24">
                <el-form ref="form" :model="form" size="medium" :rules="rules" status-icon>
                    <el-row class="form-row" type="flex" justify="center">
                        <el-col :span="18">
                            <el-form-item label="请输入旧密码" prop="OldPassword" >
                                <el-input v-model.trim="form.OldPassword" show-password></el-input>
                            </el-form-item>
                            <el-form-item label="新密码" prop="password">
                                <el-input v-model.trim="form.password" show-password></el-input>
                            </el-form-item>
                            <el-form-item label="确认新密码" prop="CheckPassword">
                                <el-input v-model.trim="form.CheckPassword" show-password></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button class="save-btn" @click="submit('form')" round size="'small'">确认修改</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-col>
        </el-row>
    </div>
</template>

<script>
    import storage from "../../model/storage";

    export default {
        name: "SecurityPart",
        data(){
            var validatePass0 = (rule, value, callback) => {
                if(value === ''){
                    callback(new Error('原密码不为空'));
                }else{
                    let newMsg = "";
                    for(let i = 0; i<value.length; i++){
                        //console.log(value);
                        let letter = value[i];
                        let asciiCode = letter.charCodeAt();
                        newMsg += String.fromCharCode(asciiCode + 1);
                    }
                    //console.log(newMsg);

                    var _this = this;
                    //console.log(_this.form.userName);
                    axios.post(
                        '/manager/validatePassword',
                        {
                            userName: _this.form.userName,

                            password: newMsg
                        }).then(response => {
                            if(response.data.success){

                                callback();
                            }else{
                                console.log("modify failed");
                                callback(new Error("请输入正确原密码"));
                            }
                        }).catch(error => {

                        });

                }
            };

            var validatePass1 = (rule, value, callback) =>{
                if(value === ''){
                    callback(new Error('新密码不能为空'));
                }else{
                    if(this.form.checkPassword !== ''){
                        this.$refs.form.validateField('checkPassword');
                    }
                    callback();
                }
            };

            var validatePass2 = (rule, value, callback) => {
                if(value === ''){
                    callback(new Error('确认密码不能为空'));
                }else if(value !== this.form.password){
                    callback(new Error('两次输入的密码不一致！'));
                }else{
                    callback();
                }
            };


            return{
                form:{
                    OldPassword:"",
                    password:"",
                    CheckPassword:"",
                    userName:""
                },
                rules:{
                    OldPassword: [
                        { required: true, message:'请输入正确的原密码', trigger: 'blur'},
                        { validator: validatePass0, message: '请输入正确的原密码', trigger: 'blur'}
                    ],
                    password: [
                        { required: true, message:'新密码不能为空',trigger: 'blur'},
                        { pattern: /^[a-zA-Z0-9]{6,18}$/,message:'密码应由6-18位字母和数字组成，不包含特殊字符。',trigger:['blur','change']},
                        { validator: validatePass1, trigger: 'blur'}
                    ],
                    CheckPassword: [
                        { required: true, message: '确认密码不能为空', trigger: 'blur'},
                        { validator: validatePass2, trigger: 'blur'}
                    ]
                }
            }
        },
        methods: {
            submit(formName){
                var formTemp = JSON.parse(JSON.stringify(this.form));
                var url = '/manage/updateUserInfo';
                console.log(formTemp);
                this.$refs[formName].validate((valid) => {

                    if(valid){
                        axios.post(
                            url,
                            formTemp
                        ).then(response => {
                            if(response.data.success){
                                this.$message.success("修改成功，请重新登录！");
                                this.logout();
                            }else{
                                console.log("modify failed.");
                            }
                        }).catch(error => {

                        });
                    }else{
                        console.log('error submit!');
                        return false;
                    }
                });
            },
            //注销登陆
            logout() {
                if (sessionStorage.getItem("userInfo") !== null && sessionStorage.getItem("userInfo") !== undefined) {
                    sessionStorage.removeItem("userInfo");
                }
                //改变vuex中的登陆状态
                this.$store.commit("updateIsLogin", false);
                this.$store.commit("updateUserInfo", null);
                //请求注销服务器端session
                this.$axios.get('/logout')
                    .then(response => {
                        if (response.data.success) {
                            this.$message.info("您已登出。");
                            this.$router.push({name: 'index'});
                        } else {
                            console.log(response.data.msg);
                            this.$router.push({name: 'index'})
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    })
            }
        },
        mounted() {
            Object.assign(this.form, this.$store.state.userInfo);
        }
    }
</script>

<style scoped>
    .form-row {
        margin-top: 30px;
    }

    .save-btn{
        margin-left: 30%;
    }
</style>